<template>
  <el-dialog
    v-model="dialogVisible"
    :title="!isEdit ? '新增批次' : '编辑批次'"
    width="40%"
    @close="dialogVisible = false"
  >
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="批次名称" prop="batchName">
        <el-input
          v-model.trim="form.batchName"
          placeholder="请输入批次名称"
          class="!w-240px"
          :controls="false"
        />
      </el-form-item>
      <el-form-item label="生成张数" prop="amount">
        <el-input-number
          v-model.trim="form.amount"
          placeholder="请输入生成张数"
          class="!w-240px"
          :min="1"
          :max="100000"
          :controls="false"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="times">
        <el-date-picker
          v-model="form.times"
          value-format="x"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="生效时间" prop="effectTime">
        <el-date-picker
          v-model="form.effectTime"
          value-format="x"
          type="datetime"
          placeholder="请选择生效时间"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="关联用户">
        <el-select
          v-model="form.userId"
          filterable
          remote
          reserve-keyword
          placeholder="请选择"
          :remote-method="remoteMethod"
          :loading="loading"
          class="!w-200px"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="权益:">
        <div class="purchase-methods">
          <div v-for="item in equity" :key="item.key">
            <div class="purchase-method">
              <el-checkbox v-model="item.checked">送{{ filter_equity[item.key] }}</el-checkbox>
              <div class="purchase-inputs">
                <div class="input-item">
                  <span class="input-label">赠送</span>
                  <el-input type="number" v-model="item.discount" />
                  <span class="input-label">{{ filter_equity[item.key] }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="formLoading">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, toRefs, computed } from 'vue'
import { getUserPage } from '@/api/member/user'
import * as LevelApi from '@/api/member/level'
import { PhysicalApi } from '@/api/allApplication/physical'

const dialogVisible = ref()
const formLoading = ref(false)
const form = ref({
  id: undefined,
  batchName: undefined,
  amount: undefined,
  times: [],
  userId: undefined
})
const isEdit = ref(false)
const loading = ref(false)
const userOptions = ref([])
const levelList = ref([])
const equity = ref([
  { key: 'experience', discount: undefined, checked: false },
  { key: 'integral', discount: undefined, checked: false }
])
const filter_equity = {
  'EXPERIENCE': '经验',
  'INTEGRAL': '积分'
}
const rules = ref({
  batchName: [{ required: true, message: '请输入批次名称', trigger: 'change' }],
  // 舌诊额度：手动输入，必须是整数，最大输入 100000
  amount: [
    {
      required: true,
      message: '请输入批次数量',
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请输入批次数量'))
        }
        callback()
      }
    }
  ],
  times: [{ required: true, message: '请选择', trigger: 'change' }]
})
const emits = defineEmits<{
  (emitStr: 'success'): void
}>()

const remoteMethod = async (query) => {
  if (query) {
    loading.value = true
    const data = await getUserPage({ pageNo: 1, pageSize: 10, mobile: query })
    userOptions.value = data.list
    loading.value = false
  } else {
    userOptions.value = []
  }
}
/** 查询会员等级列表 */
const getLevel = async () => {
  levelList.value = await LevelApi.getLevelList({})
}
/** 重置表单 */
const resetForm = () => {
  form.value = {
    id: undefined,
    batchName: undefined,
    amount: undefined,
    times: [],
    userId: undefined
  }
  formRef.value?.resetFields()
}
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  isEdit.value = type === 'edit'
  resetForm()
  equity.value = [
    { key: 'EXPERIENCE', discount: undefined, checked: false },
    { key: 'INTEGRAL', discount: undefined, checked: false }
  ]
  if (id) {
    // formLoading.value = true
    // try {
    //   form.value = await TongueTenantApi.getTenant(id)
    // } finally {
    //   formLoading.value = false
    // }
  }
}
defineExpose({ open })
const formRef = ref()
const handleSave = async () => {
  let benefitsFlag = false
  const benefits = [...equity.value]
    .filter((item) => item.checked)
    .map((item) => {
      if (!item.discount || Number(item.discount) === 0) {
        ElMessage.warning(filter_equity[item.key] + '的赠送数量不能为0')
        benefitsFlag = true
        return
      }
      const obj = {
        key: item.key,
        discount: Number(item.discount)
      }
      return obj
    })
  if (benefitsFlag) return
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const obj = {
        ...form.value,
        benefits: JSON.stringify(benefits),
        effectTime:form.value.times[0],
        expiredTime:form.value.times[1],
      }
      delete obj.times
      const data = await PhysicalApi.setPhysicalCard(obj)
      if (data) {
        emits('success')
        ElMessage({
          message: !isEdit.value ? '新增成功' : '编辑成功',
          type: 'success'
        })
        dialogVisible.value = false
      }
    } else {
      return false
    }
  })
}
onMounted(() => {
  // getTenantSimpleList().then((res: any) => {
  //   tenantList.value = res
  // })
  getLevel()
})
</script>

<style scoped lang="scss">
.purchase-methods {
  display: flex;
  flex-direction: column;
  gap: 18px;
  margin-bottom: 10px;
}

.purchase-method {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;

  .el-checkbox {
    width: 70px;
  }

  .purchase-inputs {
    display: flex;
    gap: 20px;
  }

  .input-item {
    display: flex;
    align-items: center;
    gap: 10px;

    .input-label {
      color: #606266;
    }

    .el-input {
      width: 150px;
    }
  }
}
</style>
